var i2c = require('i2c-bus');

var EARTH_GRAVITY_MS2   = 9.80665;
var SCALE_MULTIPLIER    = 0.004;

function adxl345( i2cbus, mpuaddress ) {
    if (!(this instanceof adxl345)) {
        return new adxl345(i2cbus, mpuaddress);
    }
    this.address = mpuaddress;
    this.bus = i2c.openSync(i2cbus);

    this.bus.writeByteSync(this.address, 0x31,0x0B);  // 全分辨率 ±16g
    this.bus.writeByteSync(this.address, 0x2C,0x08);  // 数据输出 25Hz 带宽12.5Hz
    this.bus.writeByteSync(this.address, 0x2D,0x08);  // 测量模式  普通工作模式
    this.bus.writeByteSync(this.address, 0x2E,0x80);  // 使能 DATA_READY 中断
}

// i2c读取adxl345原始数据
adxl345.prototype.read_raw_data = function (addr) {
    var high = this.bus.readByteSync(this.address, addr);
    var low = this.bus.readByteSync(this.address, addr+1);
    var value = (high << 8) + low; // 高8位 左移8位 组装成16位的数据
    if (value > 32768) {
        value = value - 65536;
    }
    return value;
};

// 读取器件ID
adxl345.prototype.get_devid = function() {
    var devid = this.bus.readByteSync(this.address, 0x00);
    return devid;
}

// 读取角速度值
// False (default): result is returned in m/s^2
// True           : result is returned in gs
adxl345.prototype.get_xyz_data = function(gforce = false) {
    var x = this.read_raw_data(0x32);
    var y = this.read_raw_data(0x34);
    var z = this.read_raw_data(0x36);
    var gyro_xyz = {
        x:x,
        y:y,
        z:z
    }
    x = x * SCALE_MULTIPLIER;
    y = y * SCALE_MULTIPLIER;
    z = z * SCALE_MULTIPLIER;
    var accel = {
        x: gforce ? x : x * EARTH_GRAVITY_MS2,
        y: gforce ? y : y * EARTH_GRAVITY_MS2,
        z: gforce ? z : z * EARTH_GRAVITY_MS2
    }
    return {
        gyro_xyz: gyro_xyz,
        accel: accel
    };
}
// 获取adxl345数据
adxl345.prototype.get_adxl345Data = function() {
    var xyzData = this.get_xyz_data();
    var devid = this.get_devid();
    var adxl345Data = {
        gyro_xyz: xyzData.gyro_xyz,
        accel: xyzData.accel,
        devid: devid
    }
    return adxl345Data;
}
module.exports = adxl345;
